import CryptoJS from 'crypto-js'
import qs from 'qs'

function buildSign (httpRequestConfig) {
  const headers = httpRequestConfig.headers

  const signStr = `${headers['x-client-header']}#${
        headers['x-tenant-header']}#${
        headers['x-account-header']}#${
        headers['x-user-header']}#${
        httpRequestConfig.method.toUpperCase()}#${
        httpRequestConfig.url}${buildParams(httpRequestConfig)}#${
        headers['x-timestamps']}#${
        headers['x-token-header']}#${
        httpRequestConfig.data ? headers['Content-Type'] === 'application/json' ? JSON.stringify(httpRequestConfig.data) : qs.stringify(httpRequestConfig.data) : ''}`

  const key = CryptoJS.MD5(headers['x-token-header']).toString()
  const signUrl = `${CryptoJS.enc.Base64url.stringify(CryptoJS.HmacSHA256(signStr, key))}=`
  // console.log(signUrl,signStr)
  return signUrl
}

function buildParams (httpRequestConfig) {
  const params = httpRequestConfig.params

  // console.log(httpRequestConfig,httpRequestConfig.method,httpRequestConfig.data)
  if (!params || Object.getOwnPropertyNames(params).length === 0 || httpRequestConfig.method !== 'get') { return '' }

  let p = ''

  for (const key in params) {
    const value = params[key]
    p += `${key}=${value}&`
  }

  return `?${p.substring(0, p.length - 1)}`
}

export {
  buildSign
}
